const { executeQuery } = require('../config/dbConfig');

class DraftService {
  // 获取草稿列表
  async getDrafts(userId) {
    const drafts = await executeQuery(
      'SELECT * FROM drafts WHERE user_id = ? ORDER BY updated_at DESC',
      [userId]
    );

    return drafts;
  }

  // 创建草稿
  async createDraft(userId, draftData) {
    const result = await executeQuery(
      `INSERT INTO drafts (
        user_id, 
        title,
        author,
        thoughts,
        tags,
        images,
        reading_url
      ) VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [
        userId,
        draftData.title || null,
        draftData.author || null, 
        draftData.thoughts || null,
        draftData.tags || null,
        draftData.images || null,
        draftData.reading_url || null
      ]
    );

    return result.insertId;
  }

  // 获取草稿详情
  async getDraftById(id, userId) {
    const drafts = await executeQuery(
      'SELECT * FROM drafts WHERE id = ? AND user_id = ?',
      [id, userId]
    );

    return drafts[0];
  }

  // 更新草稿
  async updateDraft(id, userId, draftData) {
    const updateFields = [];
    const updateValues = [];

    if (draftData.title) {
      updateFields.push('title = ?');
      updateValues.push(draftData.title);
    }
    if (draftData.author !== undefined) {
      updateFields.push('author = ?');
      updateValues.push(draftData.author);
    }
    if (draftData.thoughts !== undefined) {
      updateFields.push('thoughts = ?');
      updateValues.push(draftData.thoughts);
    }
    if (draftData.tags !== undefined) {
      updateFields.push('tags = ?');
      updateValues.push(draftData.tags);
    }
    if (draftData.images !== undefined) {
      updateFields.push('images = ?');
      updateValues.push(draftData.images);
    }
    if (draftData.reading_url !== undefined) {
      updateFields.push('reading_url = ?');
      updateValues.push(draftData.reading_url);
    }

    if (updateFields.length === 0) {
      throw new Error('没有要更新的字段');
    }

    updateFields.push('updated_at = CURRENT_TIMESTAMP');
    updateValues.push(id, userId);

    await executeQuery(
      `UPDATE drafts SET ${updateFields.join(', ')} WHERE id = ? AND user_id = ?`,
      updateValues
    );

    return true;
  }

  // 删除草稿
  async deleteDraft(id, userId) {
    await executeQuery(
      'DELETE FROM drafts WHERE id = ? AND user_id = ?',
      [id, userId]
    );

    return true;
  }

  // 发布草稿
  async publishDraft(id, userId) {
    // 获取草稿内容
    const draft = await this.getDraftById(id, userId);
    // 创建帖子
    const result = await executeQuery(
      `INSERT INTO posts (user_id, title, author, thoughts, tags, images, reading_url) 
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [
        userId,
        draft.title,
        draft.author,
        draft.thoughts,
        draft.tags,
        JSON.stringify(draft.images),
        draft.reading_url
      ]
    );

    // 删除草稿
    await this.deleteDraft(id, userId);

    // 获取用户昵称
    const [userInfo] = await executeQuery('SELECT nickname FROM users WHERE id = ?', [userId]);

    // 广播新书籍发布
    const wsServer = require('../utils/websocket');
    wsServer.broadcastNewBook({
      id: result.insertId,
      title: draft.title,
      author: draft.author,
      thoughts: draft.thoughts,
      tags: draft.tags ? draft.tags.split(/\s+/).filter(tag => tag) : [],
      images: typeof draft.images === 'string' ? JSON.parse(draft.images) : draft.images,
      reading_url: draft.reading_url,
      nickname: userInfo.nickname,
      createTime: new Date().toISOString()
    });

    return result.insertId;
  }
}

module.exports = new DraftService();